package com.huizhonglm.diap.ui.tab;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.bruce.common.utils.EmptyUtil;
import com.bruce.pullrefresh.PullToRefreshBase;
import com.bruce.pullrefresh.PullToRefreshListView;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.model.shop.ShopInfo;
import com.huizhonglm.diap.core.config.Constants;
import com.huizhonglm.diap.core.location.LocationService;
import com.huizhonglm.diap.core.location.LocationUtil;
import com.huizhonglm.diap.core.storage.model.LocationInfo;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.presenters.tab.TabhostNearPresenter;
import com.huizhonglm.diap.ui.BaseFragment;
import com.huizhonglm.diap.ui.shop.SearchActivity;
import com.huizhonglm.diap.ui.shop.ShopDetailActivity;
import com.huizhonglm.diap.ui.tab.iView.TabhostNearIView;
import com.huizhonglm.diap.widget.LoadView;
import com.huizhonglm.diap.widget.expandTab.ExpandTabMenu;
import com.huizhonglm.diap.widget.expandTab.MenuData;
import com.huizhonglm.diap.widget.expandTab.MenuGridSignle;
import com.huizhonglm.diap.widget.expandTab.MenuInfo;
import com.huizhonglm.diap.widget.expandTab.MenuListDouble;
import com.huizhonglm.diap.widget.expandTab.MenuListSignle;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述当前类的作用
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-01 23:27
 */
public class TabhostNearFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener,
        LoadView.OnLoadAgainListener, TabhostNearIView, PullToRefreshBase.OnRefreshListener2<ListView> {

    private LayoutInflater mInflater;
    private View rootView;
    private PullToRefreshListView pullView;
    private ListView mListView;
    private LoadView loadView;
    private TextView currentLocaTxt;
    private TextView refreshLocaTxt;
    private String categoryId;
    private String isParent;
    private double radius;
    private String smartSortId;
    private String filterId;

    private MenuData mMenuData;
    private List<ShopInfo> mData;
    private TabhostNearAdapter mAdapter;
    private TabhostNearPresenter mPresenter;

    private boolean isVisible = false;
    private boolean isPrepared = false;

    private ExpandTabMenu expandTabView;
    private ArrayList<View> mViewArray = new ArrayList<>();
    private MenuListDouble categoryMenu;
    private MenuListSignle radiusMenu;
    private MenuListSignle smartSortMenu;
    private MenuGridSignle filterMenu;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mPresenter = new TabhostNearPresenter(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.mInflater = inflater;
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_tabhost_near, container, false);
        }
        View searchIbtn = rootView.findViewById(R.id.title_search_ibtn);
        expandTabView = (ExpandTabMenu) rootView.findViewById(R.id.near_extab_view);
        loadView = (LoadView) rootView.findViewById(R.id.load_view);
        currentLocaTxt = (TextView) rootView.findViewById(R.id.current_location_txt);
        refreshLocaTxt = (TextView) rootView.findViewById(R.id.refresh_location_txt);
        pullView = (PullToRefreshListView) rootView.findViewById(R.id.tabhost_near_list);
        pullView.setMode(PullToRefreshBase.Mode.BOTH);
        pullView.setOnRefreshListener(this);
        mListView = pullView.getRefreshableView();
        mListView.setOnItemClickListener(this);
        refreshLocaTxt.setOnClickListener(this);
        searchIbtn.setOnClickListener(this);
        loadView.setDataView(pullView, this);

        isPrepared = true;
        return rootView;
    }

    private void onRefresh(View view, MenuInfo info) {
        expandTabView.onPressBack();
        int position = getPositon(view);
        if (position >= 0 && !expandTabView.getTitle(position).equals(info.getName())) {
            expandTabView.setTitle(info.getName(), position);
        }
        if (info != null){
            switch (info.getType()) {
                case TabhostNearPresenter.EX_TAB_CATEGORY:
                    categoryId = info.getId();
                    isParent = info.getIsParent();
                    break;
                case TabhostNearPresenter.EX_TAB_RADIUS:
                    if ("-9".equals(info.getId())) {
                        radius = 0;
                    } else {
                        radius = Double.valueOf(info.getId());
                    }
                    break;
                case TabhostNearPresenter.EX_TAB_SMARTSORT:
                    smartSortId = info.getId();
                    break;
                case TabhostNearPresenter.EX_TAB_FILTER:
                    filterId = info.getId();
                    break;
            }
            loadView.showProgress();
            mPresenter.loadData(Constants.LOAD_INIT, isParent, categoryId, radius, smartSortId, filterId);
        }
    }

    public void setLocationPoint(LocationInfo info) {
        if (isPrepared && isVisible) {
            setPointName(info);
            loadView.showProgress();
            mPresenter.loadData(Constants.LOAD_INIT, isParent, categoryId, radius, smartSortId, filterId);
        }
    }

    private void setPointName(LocationInfo info){
        if (refreshLocaTxt != null && currentLocaTxt != null) {
            refreshLocaTxt.setVisibility(View.VISIBLE);
            if (info != null) {
                currentLocaTxt.setText("当前：" + info.getDistrict() + info.getPoiName());
            } else {
                currentLocaTxt.setText("定位失败，稍后刷新当前位置");
            }
        }
    }

    private int getPositon(View tView) {
        for (int i = 0; i < mViewArray.size(); i++) {
            if (mViewArray.get(i) == tView) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        boolean userVisibleHint = getUserVisibleHint();
        if (userVisibleHint) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
        }
    }

    @Override
    public void onVisible() {
        if (isPrepared && isVisible) {
            setPointName(LocationUtil.getLocation());
            onLoadAgain();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        mPresenter.loadData(Constants.LOAD_DROP, isParent, categoryId, radius, smartSortId, filterId);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        mPresenter.loadData(Constants.LOAD_MORE, isParent, categoryId, radius, smartSortId, filterId);
    }

    @Override
    public void onLoadAgain() {
        if (mMenuData == null) {
            mPresenter.loadMenu();
        }
    }

    @Override
    public void onLoadDataSuccess(String pullFlag, List<ShopInfo> data) {
        switch (pullFlag) {
            case Constants.LOAD_INIT:
                this.mData = data;
                updatePage(data);
                loadView.showDataView();
                break;
            case Constants.LOAD_DROP:
                this.mData = data;
                updatePage(data);
                pullView.onRefreshComplete();
                break;
            case Constants.LOAD_MORE:
                this.mData.addAll(data);
                updatePage(data);
                pullView.onRefreshComplete();
                break;
        }
    }

    @Override
    public void onLoadDataFailure(String pullFlag) {
        switch (pullFlag) {
            case Constants.LOAD_INIT:
                loadView.showErrorView();
                break;
            case Constants.LOAD_DROP:
                ToastUtil.makeTextShort("刷新失败");
                pullView.onRefreshComplete();
                break;
            case Constants.LOAD_MORE:
                ToastUtil.makeTextShort("加载更多失败");
                pullView.onRefreshComplete();
                break;
        }
    }

    @Override
    public void onLoadDataEmpty(String pullFlag) {
        switch (pullFlag) {
            case Constants.LOAD_INIT:
                loadView.showEmptyView(null);
                break;
            case Constants.LOAD_DROP:
                ToastUtil.makeTextShort("列表已经是最新");
                pullView.onRefreshComplete();
                break;
            case Constants.LOAD_MORE:
                ToastUtil.makeTextShort("到底部啦");
                pullView.onRefreshComplete();
                break;
        }
    }

    @Override
    public void onLoadMenuSuccess(MenuData menu) {
        if (menu != null) {
            expandTabView.setVisibility(View.VISIBLE);
            initDorpDownMenu(menu);
            mPresenter.loadData(Constants.LOAD_INIT, isParent, categoryId, radius, smartSortId, filterId);
        } else {
            expandTabView.setVisibility(View.GONE);
            loadView.showErrorView();
        }
    }

    @Override
    public void onLoadMenuFailure() {
        expandTabView.setVisibility(View.GONE);
        loadView.showErrorView();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ShopInfo shop = (ShopInfo) parent.getAdapter().getItem(position);
        if (shop != null) {
            Intent intent = new Intent(getActivity(), ShopDetailActivity.class);
            intent.putExtra("shopId", shop.getSid());
            startActivity(intent);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.refresh_location_txt:
                refreshLoaction();
                break;
            case R.id.title_search_ibtn:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
        }
    }

    private void updatePage(List<ShopInfo> data){
        setPullViewMode(data);
        if (mAdapter == null) {
            mAdapter = new TabhostNearAdapter(mInflater, mData);
            mListView.setAdapter(mAdapter);
        } else {
            mAdapter.setData(mData);
            mAdapter.notifyDataSetChanged();
        }
    }

    private void setPullViewMode(List<ShopInfo> data){
        if (!EmptyUtil.isEmpty(data)) {
            if (mData.size() >= Constants.PAGE_SIZE) {
                if (data.size() < Constants.PAGE_SIZE) {
                    pullView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                } else {
                    pullView.setMode(PullToRefreshBase.Mode.BOTH);
                }
            } else {
                pullView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
            }
        }
    }

    private void initDorpDownMenu(MenuData menuData){
        mMenuData = menuData;
        List<MenuInfo> categoryList = menuData.getCategoryData();
        List<MenuInfo> smartSortList = menuData.getSmartSortData();
        List<MenuInfo> filterList = menuData.getFilterData();
        List<MenuInfo> radiusList = menuData.getRadiusData();

        categoryMenu = new MenuListDouble(getActivity(), categoryList);
        radiusMenu = new MenuListSignle(getActivity(), radiusList);
        smartSortMenu = new MenuListSignle(getActivity(), smartSortList);
        filterMenu = new MenuGridSignle(getActivity(), filterList);

        categoryMenu.setTag("height");
        radiusMenu.setTag("height");
        smartSortMenu.setTag("wrapContent");
        filterMenu.setTag("wrapContent");

        mViewArray.add(categoryMenu);
        mViewArray.add(radiusMenu);
        mViewArray.add(smartSortMenu);
        mViewArray.add(filterMenu);
        ArrayList<String> mTextArray = new ArrayList<>();
        mTextArray.add("全部");
        mTextArray.add("全城");
        mTextArray.add("智能排序");
        mTextArray.add("筛选");
        expandTabView.setValue(mTextArray, mViewArray);
        categoryMenu.setOnSelectListener(new MenuListDouble.OnSelectListener() {
            @Override
            public void getValue(MenuInfo info) {
                onRefresh(categoryMenu, info);
            }
        });
        radiusMenu.setOnSelectListener(new MenuListSignle.OnSelectListener() {
            @Override
            public void getValue(MenuInfo info) {
                onRefresh(radiusMenu, info);
            }
        });
        smartSortMenu.setOnSelectListener(new MenuListSignle.OnSelectListener() {
            @Override
            public void getValue(MenuInfo info) {
                onRefresh(smartSortMenu, info);
            }
        });
        filterMenu.setOnSelectListener(new MenuGridSignle.OnSelectListener() {
            @Override
            public void getValue(MenuInfo info) {
                onRefresh(filterMenu, info);
            }
        });
    }

    private void refreshLoaction(){
        currentLocaTxt.setText("正在定位，请稍后...");
        refreshLocaTxt.setVisibility(View.GONE);
        getActivity().startService(new Intent(getActivity(), LocationService.class));
    }
}
